import banWord
import phraseSearch
import judgeTime
import BM25
import tools
import pickle
import jieba
import extendWord



def search(searchContext,search_time,search_sort,extend_dict):
    iftitle = 0
    ifphrase = 0
    ifban = 0

    # 获取用户输入
    #searchContext = input("please input your search:")
    print(searchContext)

    # 选择数据集
    if "t:" == searchContext[0:2]:
        iftitle = 1
        searchContext = searchContext[2:]

    # 判断是否存在屏蔽词
    if iftitle:
        indexfile = "out/invertIndex_title.json"
    else:
        indexfile = "out/invertIndex.json"

    result = banWord.banWord(searchContext,indexfile)
    # print(result)
    if result["ban"] != -1:
        searchContext = result["search"]
        ifban = 1
        banfilelist = result["banfile"]
        banfilelist = sorted(banfilelist)
        print("banfile:",banfilelist)

    # 判断是否需要短语检索
    # print(searchContext)
    phraselist = phraseSearch.searchPhrase(searchContext)
    # print(phraselist)
    if len(phraselist) > 0:
        ifphrase = 1
        result = phraseSearch.phraseSearch(phraselist,indexfile)
        # print(result)
        phrasefile = []
        for i in range(len(phraselist)):
            if result[i] != -1:
                phrasefile.extend(result[i].keys())
        phrasefile = sorted(phrasefile)
        print("phrasefile:",phrasefile)

    searchwordlist = list(jieba.cut_for_search(searchContext))
    extend_word_list = searchwordlist
    #extend_word_list = extendWord.extend_search_word(searchwordlist, extend_dict)
    print("asd",extend_word_list)
    # -----------------------------iftitle判断是否使用标题数据集-------------------------------
    # -----------------------------ifban判断是否使用屏蔽文章列表-------------------------------
    # -----------------------------ifphrase判断是否使用短语检索-------------------------------
    # ----------------------------banfilelist:屏蔽文章列表，phrasefile：短语所在文章列表--------------------------------

    # 千芊的部分
    #time_limit=""
    doc_in_time=judgeTime.judgeTime(search_time)
    print("query",end=" ")
    print(searchContext)
    doc_in_index=BM25.pre(extend_word_list,iftitle)

    print("doc_in_time",end=" ")
    print(doc_in_time)
    print("doc_in_index", end=" ")
    print(doc_in_index)

    set1 = set(doc_in_time)
    set2 = set(doc_in_index)
    temp = set1 & set2
    if ifphrase:
        set3 = set(phrasefile)
        result = list(temp & set3)
    else:
        if ifban:
            set3 =  set(banfilelist)
            result = list(temp - set3)
        else:
            result = list(temp)
    print(result)

    #result是最后要计算相关度的文章名列表
    doc_output=BM25.bm25(extend_word_list,iftitle,result,search_sort)
    #bm25(query, iftitle, doc_list)
    return doc_output,extend_word_list

#search()

    # 输出部分（后面再加）


